package com.jshoperxms.controller.mall.backstage.membercart;

import com.jshoperxms.Response;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.enums.MemberCartEnums;
import com.jshoperxms.controller.utils.enums.ProductEnums;
import com.jshoperxms.controller.utils.maths.Arith;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.GoodsTypeT;
import com.jshoperxms.entity.MemberCartT;
import com.jshoperxms.entity.MemberRechargeT;
import com.jshoperxms.entity.ProductT;
import com.jshoperxms.service.MemberCartTService;
import com.jshoperxms.service.ProductTService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 17/1/4.
 * Des:
 */
@Controller
@RequestMapping("/mall/membercart")
public class MemberCartTController extends BaseTController implements IBaseCtrl<MemberCartT> {

    private Map<String,Object> responsedata=new HashMap<>();


    @Resource
    private MemberCartTService memberCartTService;

    @Resource
    private ProductTService productTService;

    @Override
    public ResponseEntity save(@RequestBody MemberCartT rq) {
        if(StringUtils.isBlank(rq.getProductid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }else{
            ProductT p=this.productTService.findByPK(ProductT.class,rq.getProductid());
            if(p!=null){
                MemberCartT bean=new MemberCartT();
                bean.setId(this.serial.Serialid(SerialKeys.MEMBERCART));
                bean.setAddtime(DateTools.getSystemTimeBi());
                bean.setBasicuserid(BaseTools.getAdminCreateId());
                bean.setBasicusername(BaseTools.getAdminCreateName());
                bean.setCartactiontag(MemberCartEnums.MemberCartActionTag.SYSGIFT_EIGHT_NUM.getState());
                bean.setCartstatus(MemberCartEnums.MemberCartStatus.NEWADDTOCART_ONE_NUM.getState());
                bean.setCarttag(StaticKey.EMPTY);
                bean.setChangeprice(BigDecimal.valueOf(Arith.sub(p.getSaleprice().doubleValue(),p.getMemberprice().doubleValue())));
                bean.setGoodsid(p.getGoodsid());
                bean.setHtmlpath(p.getHtmlpath());
                if(StringUtils.isBlank(p.getStoreid())){
                    bean.setIsmall(MemberCartEnums.MemberCartIsMall.SELF_ONE_NUM.getState());
                }else{
                    bean.setIsmall(MemberCartEnums.MemberCartIsMall.STORE_TWO_NUM.getState());
                }
                bean.setIswishlist(MemberCartEnums.MemberCartIsWishList.DISADD_TWO_NUM.getState());
                bean.setMainimg(p.getMainimg());
                bean.setMemberid(rq.getMemberid());
                bean.setMembername(rq.getMembername());
                bean.setMemberprice(p.getMemberprice());
                bean.setNeedquantity(rq.getNeedquantity());
                bean.setPoints(p.getPoints());
                bean.setProductid(p.getProductid());
                bean.setProductname(p.getProductname());
                bean.setPromotioncometag(MemberCartEnums.MemberCartPromotionComeTag.SYSGIFT_EIGHT_NUM.getState());
                bean.setPsn(p.getPsn());
                bean.setRporderid(StaticKey.EMPTY);
                bean.setSaleprice(p.getSaleprice());
                bean.setSamecartbatchid(StaticKey.EMPTY);
                bean.setSmainimg(p.getSmainimg());
                bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                if(p.getStock()>0){
                    bean.setStockstatus(ProductEnums.ProductStock.HAVE.getState());
                }else{
                    bean.setStockstatus(ProductEnums.ProductStock.NO.getState());
                }
                bean.setStoreid(p.getStoreid());
                bean.setStorename(p.getStorename());
                bean.setSubtotal(BigDecimal.valueOf(Arith.add(bean.getMemberprice().doubleValue(),Double.valueOf(bean.getNeedquantity()))));
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(1);
                bean.setWeight(p.getWeight());
                bean.setWeightunit(p.getWeightunit());
                bean.setPskuvals(p.getPskuvals());
                bean.setCreatetime(DateTools.getSystemTimeBi());
                this.memberCartTService.save(bean);
                responsedata.put(TagWords.SUCCESS, true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }

        return Response.success(responsedata);
    }


    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody MemberCartT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            MemberCartT bean=this.memberCartTService.findByPK(MemberCartT.class,rq.getId());
            if(bean!=null){
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,TagWords.INVALIDDATA);
            }
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody MemberCartT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getId(), TagWords.SPLITDOT);
            for(String s:ids){
                MemberCartT bean=this.memberCartTService.findByPK(MemberCartT.class, s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.memberCartTService.update(bean);
                }
            }
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody MemberCartT rq) throws ParseException {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            MemberCartT bean=this.memberCartTService.findByPK(MemberCartT.class,rq.getId());
            if(bean!=null){
                if(!StringUtils.equals(StaticKey.EMPTY,bean.getRporderid())){
                    responsedata.put(TagWords.SUCCESS,false);
                    responsedata.put(TagWords.MSG,WarnWrods.ERROR_CARTHAVE_RP_ORDER);
                }else{
                    ProductT p=this.productTService.findByPK(ProductT.class,rq.getProductid());
                    if(p!=null){
                        bean.setBasicuserid(BaseTools.getAdminCreateId());
                        bean.setBasicusername(BaseTools.getAdminCreateName());
                        bean.setChangeprice(BigDecimal.valueOf(Arith.sub(rq.getSaleprice().doubleValue(),rq.getMemberprice().doubleValue())));
                        bean.setGoodsid(p.getGoodsid());
                        bean.setHtmlpath(p.getHtmlpath());
                        if(StringUtils.isBlank(p.getStoreid())){
                            bean.setIsmall(MemberCartEnums.MemberCartIsMall.SELF_ONE_NUM.getState());
                        }else{
                            bean.setIsmall(MemberCartEnums.MemberCartIsMall.STORE_TWO_NUM.getState());
                        }
                        bean.setMainimg(p.getMainimg());
                        bean.setMemberprice(p.getMemberprice());
                        bean.setNeedquantity(rq.getNeedquantity());
                        bean.setPoints(p.getPoints());
                        bean.setProductid(p.getProductid());
                        bean.setProductname(p.getProductname());
                        bean.setPsn(p.getPsn());
                        bean.setSaleprice(p.getSaleprice());
                        bean.setSmainimg(p.getSmainimg());
                        if(p.getStock()>0){
                            bean.setStockstatus(ProductEnums.ProductStock.HAVE.getState());
                        }else{
                            bean.setStockstatus(ProductEnums.ProductStock.NO.getState());
                        }
                        bean.setStoreid(p.getStoreid());
                        bean.setStorename(p.getStorename());
                        bean.setSubtotal(BigDecimal.valueOf(Arith.add(bean.getMemberprice().doubleValue(),Double.valueOf(bean.getNeedquantity()))));
                        bean.setUpdatetime(DateTools.getSystemTimeBi());
                        bean.setVersiont(bean.getVersiont()+1);
                        bean.setWeight(p.getWeight());
                        bean.setWeightunit(p.getWeightunit());
                        bean.setPskuvals(p.getPskuvals());
                        this.memberCartTService.update(bean);
                        responsedata.put(TagWords.SUCCESS,true);
                        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
                    }else{
                        responsedata.put(TagWords.SUCCESS,false);
                        responsedata.put(TagWords.MSG,WarnWrods.EMPTY_RECORD);
                    }
                }
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,WarnWrods.EMPTY_RECORD);
            }
        }
        return Response.success(responsedata);
    }


    /**
     * 查询所有新加入购物车的商品
     * @param rq
     * @return
     */
    @RequestMapping(value="/findAllCartByMemberId",method= RequestMethod.POST)
    public ResponseEntity findAllCartByMemberId(@RequestBody MemberCartT rq){
        if(StringUtils.isBlank(rq.getMemberid())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            Criterion criterion= Restrictions.and(Restrictions.eq(TagWords.STATUS,BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("cartstatus",MemberCartEnums.MemberCartStatus.NEWADDTOCART_ONE_NUM.getState()));
            List<MemberCartT>list=this.memberCartTService.findByCriteria(MemberCartT.class,criterion, Order.desc(TagWords.UPDATETIME));
            responsedata.put(TagWords.BEANLIST,list);
            responsedata.put(TagWords.SUCCESS, true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);

        }
        return Response.success(responsedata);

    }

    @Override
    public ResponseEntity findAll() {
        return null;
    }

    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        return null;
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {

    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {

    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {

    }

    @RequestMapping(value="/findMemberCartByPage",method= RequestMethod.POST)
    public ResponseEntity findMemberCartByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        //检查是否有自定义搜索内容 1标示进行自定义搜索逻辑
        findMemberCartCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    private void findMemberCartCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        //如果有自定义搜索
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion= Restrictions.and(Restrictions.eq(TagWords.STATUS,BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("memberid",searchModel.getMemberid()));
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("productname",search,MatchMode.ANYWHERE));
            }
            int records=this.memberCartTService.count(MemberCartT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<MemberCartT> list = this.memberCartTService.findByCriteriaByPage(
                    MemberCartT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processMemberCartPageList(list);
        }else{
            if(StringUtils.isNotBlank(search)){
                filterMemberCartSearch(searchModel,search);
            }else{
                findMemberCartDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }


    private void filterMemberCartSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize=searchModel.getLength();
        Criterion criterion= Restrictions.and(Restrictions.eq(TagWords.STATUS,BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("memberid",searchModel.getMemberid()));
        if(StringUtils.isNotBlank(search)){
            criterion=Restrictions.and(criterion).add(Restrictions.like("productname",search,MatchMode.ANYWHERE));
        }
        int records=this.memberCartTService.count(MemberCartT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<MemberCartT> list = this.memberCartTService.findByCriteriaByPage(
                MemberCartT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processMemberCartPageList(list);
    }


    private void findMemberCartDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize=searchModel.getLength();
        Criterion criterion= Restrictions.and(Restrictions.eq(TagWords.STATUS,BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("memberid",searchModel.getMemberid()));
        int records=this.memberCartTService.count(MemberCartT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<MemberCartT> list = this.memberCartTService.findByCriteriaByPage(
                MemberCartT.class, criterion, Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processMemberCartPageList(list);
    }

    private void processMemberCartPageList(List<MemberCartT> list) {
        List<Map<String,Object>>data=new ArrayList<>();
        for (MemberCartT bean:list){
            if(StringUtils.isBlank(bean.getSmainimg())){
                bean.setSmainimg(bean.getMainimg());
            }
            Map<String,Object>cellMap=new HashMap<>();
            cellMap.put("id", bean.getProductid());
            cellMap.put("goodsid",bean.getGoodsid());
            cellMap.put("smainimg",bean.getSmainimg());
            cellMap.put("productname", bean.getProductname());
            cellMap.put("pskuvals",bean.getPskuvals());
            cellMap.put("memberprice", bean.getMemberprice());
            cellMap.put("stockstatus", ProductEnums.ProductStock.getName(bean.getStockstatus()));
            cellMap.put("weight", bean.getWeight()+bean.getWeightunit());
            cellMap.put("productid", bean.getProductid());
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA, data);
    }

    @Override
    public void processPageList(List<MemberCartT> list) {

    }

    @Override
    public boolean checkDuplicates(String str) {
        return false;
    }
}
